package com.ssh;

import java.util.ArrayList;
import java.util.List;

import org.junit.Test;

public class SpiralOrder_54 {
	@Test
	public void test () {
		int[][] matrix = {{1,2,3},{4,5,6},{7,8,9},{10,11,12},{13,14,15}};
		System.out.println(spiralOrder(matrix));
	}
	
	public List<Integer> spiralOrder(int[][] matrix) {
		List<Integer> list = new ArrayList<Integer>();
		if (matrix.length == 0) {
			return list;
		}
		int rowStart = 0;
		int rowEnd = matrix.length-1;
		int colsStart = 0;
		int colsEnd = matrix[0].length-1;
		while (rowStart <= rowEnd && colsStart <= colsEnd) {
			for (int i = colsStart; i <= colsEnd; i++) {
				list.add(matrix[rowStart][i]);
			}
			rowStart++;
			for (int i = rowStart; i <= rowEnd; i++) {
				list.add(matrix[i][colsEnd]);
			}
			colsEnd--;
			if (rowStart <= rowEnd) {
				for (int i = colsEnd; i >= colsStart; i--) {
					list.add(matrix[rowEnd][i]);
				}
				
			}
			rowEnd--;
			if (colsStart <= colsEnd) {
				for (int i = rowEnd; i >= rowStart; i--) {
					list.add(matrix[i][colsStart]);
				}
			}
			colsStart++;
		}
		return list;
    }
}
